<?php

class User_Action_Connect_Google extends Action
{
	function execute($request)
	{
		require_once 'googleapi/apiClient.php';

		$client = new apiClient();

		$client -> setApplicationName('Google About Me!');

		$client -> setScopes(array(
			'http://www.google.com/m8/feeds/',
			'https://www.googleapis.com/auth/userinfo.profile',
			'https://www.googleapis.com/auth/userinfo.email'
		));

		// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
		// Visit https://code.google.com/apis/console?api=contacts to generate your
		// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
		$client -> setClientId($google_key);
		$client -> setClientSecret($google_secret);
		$client -> setRedirectUri(Agilet::getUrl('/user/connect/google'));

		//$client->setDeveloperKey('insert_your_developer_key');

		if (isset($_GET['code']))
		{
			$client -> authenticate();
			$_SESSION['token'] = $client -> getAccessToken();
			$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
			header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
		}

		if (isset($_SESSION['token']))
		{
			$client -> setAccessToken($_SESSION['token']);
		}

		if (isset($_REQUEST['logout']))
		{
			unset($_SESSION['token']);
			$client -> revokeToken();
		}

		if ($client -> getAccessToken())
		{
			$req = new apiHttpRequest('https://www.googleapis.com/oauth2/v1/userinfo?alt=json');

			$val = $client -> getIo() -> authenticatedRequest($req);

			$data = json_decode($val -> getResponseBody(), 1);

			$result = Mapper::fromGoogle($data);

			processCentralServiceResponseData($result);

			// The access token may have been updated lazily.
			// $_SESSION['token'] = $client -> getAccessToken();
		}
		else
		{
			$auth = $client -> createAuthUrl();
		}

		if (isset($auth))
		{
			header('location: ' . $auth);
		}
		else
		{
			print "<a class=logout href='?logout'>Logout</a>";
		}
	}

}
